import matplotlib.pyplot as plt
import numpy as np

# 图像数据 二维数组形式显示像素值
def line(x1,x2, y1,y2):
    x = x1; y = y1
    delta_x = abs(x2-x1); delta_y = abs(y2-y1)
    sign_x = 0 if x2==x1 else (1 if x2>x1 else -1)
    sign_y = 0 if y2==y1 else (1 if y2>y1 else -1)
    # 假设斜率存在
    k0 = -delta_x; k = k0+2*delta_y
    # 坐标
    img = np.zeros((200,200))
    for i in range(1, delta_x+1):
        img[200-y-1, x] = 255
        if k>=0:
            y += sign_y
            k += (2*delta_y-2*delta_x)
        else: 
            k += 2*delta_y
        x += sign_x
    return img

img = line(10,190, 126,60)

# 保存图像
plt.imsave("直线.png", img, cmap='gray_r')

# 显示图像
fig=plt.figure()
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray_r')
plt.show()